package com.bw.car.service.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.bw.car.domain.Car;
import com.bw.car.domain.OutIn;
import com.bw.car.mapper.CarMapper;
import com.bw.car.service.CarService;
import com.bw.car.vo.CarVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

@Service
public class CarServiceImpl implements CarService {
	
	@Autowired
	CarMapper carMapper;

	@Override
	public boolean insert(Car car,String inTime) {
		
		try {
			
			//1.判断汽车在库存表是否存在，如果不存在则插入顺序分别为车辆表、现存车辆表、和车辆出入库记录表
			if(carMapper.selectByCno(car.getCno())==0) {
				carMapper.insert(car);//添加到车辆表	
			}
			
			//2.添加到现存车辆表
			carMapper.insertStore(car.getId(),inTime,car.getCno());
			//3车辆出入记录表
			carMapper.insertOutIn(car.getId(), inTime);
			
			return true;
			
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("增加失败");
		}
		
	}

	
	@Override
	public PageInfo<Car> selects(Car car, Integer pageNum, Integer pageSize) {
		
		PageHelper.startPage(pageNum, pageSize);
		List<Car> list = carMapper.selects(car);
		
		return new PageInfo<Car>(list);
	}


	@Override
	public Car getCarInfo(String cno) {
		// TODO Auto-generated method stub
		return carMapper.getCarInfo(cno);
	}


	@Override
	public int getMoneyByCid(Integer cid) {
		// TODO Auto-generated method stub
		return carMapper.getMoneyByCid(cid);
	}


	@Override
	public void outStore(OutIn outIn) {
	
		 try {
			 
			 //1删除 现存表记录
			 carMapper.deleteStoreById(outIn.getCid());
			 
			 
			 //2 更新出入库记录表
				 //2.1 先取出该车辆的最后一次入库的记录信息
				 OutIn lastOne = carMapper.getLastOne(outIn.getCid());
				 lastOne.setMoneySS(outIn.getMoneySS());
				 lastOne.setMoneyYS(outIn.getMoneyYS());
				 lastOne.setOutTime(new Date());
				 //2.2 执行更新
				 carMapper.updateOutIn(lastOne);
			
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("出库失败");
		}
		 
		
	}


	@Override
	public List<OutIn> getReport(CarVO carVO) {
		// TODO Auto-generated method stub
		return carMapper.getReport(carVO);
	}


}
